package com.codez.gznx.excel;

import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.List;

import org.springframework.stereotype.Service;

/**
 * 
 * @author dechao.zheng
 * @createTime: 2019-09-23 06:13:20	
 *
 */

@Service
public class ValidateService {

	private static final String NULL_ERROR_MSG = "[{0}]不能为空";
	private static final String EMPTY_ERROR_MSG = "[{0}]不能为空";
	
	
	public boolean valid(ValidableEntity ve) {
		Field[] fields = ve.getClass().getDeclaredFields();
		for (Field field : fields) {
			if(field.isAnnotationPresent(ValidateField.class)) {
				field.setAccessible(true);
				ValidateField vf = field.getAnnotation(ValidateField.class);
				// 注意短路&&
				if(ValidateFieldRule.NOT_NULL == vf.rule()) {
					checkNotNull(ve , field , vf);
				}else if(ValidateFieldRule.NOT_EMPTY == vf.rule()){
					checkNotEmpty(ve , field , vf);
				}
			}
		}
		return !ve.hasError();
	}


	/**
	 * -- null判断
	 * @param obj
	 * @param field
	 * @param vf
	 */
	private boolean checkNotNull(ValidableEntity validableEntity, Field field, ValidateField vf) {
		try {
			if(field.get(validableEntity) == null) {
				String msg = "".equals(vf.msg()) ? NULL_ERROR_MSG : vf.msg();
				msg = MessageFormat.format(msg, vf.name());
				validableEntity.addError(field.getName(), msg);
				return false;
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return true;
	}
	/**
	 * -- 字符串空字符判断
	 * @param obj
	 * @param field
	 * @param vf
	 * @return
	 */
	private boolean checkNotEmpty(ValidableEntity validableEntity, Field field, ValidateField vf) {
		try {
			if(field.get(validableEntity) == null || 
				(field.getType().equals(String.class)  && ((String)field.get(validableEntity)).trim().length() == 0 )) {
				String msg = "".equals(vf.msg()) ? EMPTY_ERROR_MSG: vf.msg();
				msg = MessageFormat.format(msg, vf.name());
				validableEntity.addError(field.getName(), msg);
				return false;
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	
	public Boolean validList(List<? extends ValidableEntity> entities) {
		boolean res = true;
		for (ValidableEntity validableEntity : entities) {
			if(!valid(validableEntity)) {
				res = false;
			}
		}
		return res;
	}
	
	
	public static void main(String[] args) {
		User user = new User();
		user.setUsername("123");
		if(!new ValidateService().valid(user)) {
			System.out.println(user.getErrorMsg());
		}
		System.out.println(user);
	}
	
}
